package com.maiji.cloud.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.google.common.collect.Lists;
import com.maiji.cloud.entities.manager.Menu;
import com.maiji.cloud.entities.manager.RoleMenu;
import com.maiji.cloud.mapper.RoleMenuMapper;
import com.maiji.cloud.response.BaseDataResDto;
import com.maiji.cloud.response.BaseResDto;
import com.maiji.cloud.response.Status;
import com.maiji.cloud.service.MenuService;
import com.maiji.cloud.service.RoleMenuService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.maiji.cloud.utils.UUID_MD5;
import org.eclipse.jetty.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class RoleMenuServiceImpl extends ServiceImpl<RoleMenuMapper, RoleMenu> implements RoleMenuService {

    @Autowired
    private MenuService menuService;

    @Override
    public Boolean addRoleMenus(String roleId, List<String> menuIds) {
        if (menuIds == null ||  menuIds.size() == 0) return false;
        List<RoleMenu> roleMenuList = menuIds.parallelStream().map(menuId ->
                new RoleMenu().setUuId(UUID_MD5.getUUID()).setRoleId(roleId).setMenuId(menuId)).collect(Collectors.toList());;
        return insertBatch(roleMenuList);
    }

    @Override
    public BaseDataResDto<List<Menu>> findAllMenus(String roleId) {
        List<String> menuIds = Lists.newArrayList();
        if (StringUtil.isNotBlank(roleId)) {
            Wrapper<RoleMenu> wrapper = new EntityWrapper<RoleMenu>().eq("role_id", roleId);
            menuIds = selectList(wrapper).parallelStream().map(RoleMenu::getMenuId).collect(Collectors.toList());
        }
        EntityWrapper<Menu> entityWrapper = new EntityWrapper<>();
        if (menuIds.size() > 0) entityWrapper.in("uu_id", menuIds);
        List<Menu> menuList = menuService.selectList(entityWrapper);
        return new BaseDataResDto<List<Menu>>(Status.SUCCESS).setData(menuList);
    }

    @Override
    public BaseResDto editRoleMenu(String roleId, List<String> menuIds, Boolean add) {
        if (add) {
            List<RoleMenu> roleMenuList = menuIds.parallelStream().map(menuId ->
                    new RoleMenu().setUuId(UUID_MD5.getUUID()).setRoleId(roleId).setMenuId(menuId)).collect(Collectors.toList());
            if (! insertBatch(roleMenuList)) return new BaseResDto(Status.ERROR);
        } else {
            Wrapper<RoleMenu> menuWrapper = new EntityWrapper<RoleMenu>()
                    .eq("role_id", roleId)
                    .in("menu_id", menuIds);
            if (! delete(menuWrapper)) return new BaseResDto(Status.ERROR);
        }
        return new BaseResDto(Status.SUCCESS);
    }

}
